package com.qianfeng.openapi.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openapi.zuul.domain.ESLogBean;
import com.qianfeng.openapi.zuul.exception.ExceptionDict;
import com.qianfeng.openapi.zuul.utils.DateUtils;
import com.qianfeng.openapi.zuul.utils.SysConstant;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/5
 * @Time: 上午10:08
 */
//@Component
public class ESLogFilter extends ZuulFilter {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;//"post"
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext context = RequestContext.getCurrentContext();
            HttpServletRequest request = context.getRequest();
            ESLogBean esLogBean = new ESLogBean();
            String apiName = request.getParameter(SysConstant.METHOD);
            String appKey = request.getParameter(SysConstant.APPKEY);
            String param_json = request.getParameter(SysConstant.PARAM_JSON);

            esLogBean.setApiName(apiName);
            esLogBean.setAppKey(appKey);
            esLogBean.setRemoteIp(request.getRemoteAddr());
            esLogBean.setRequestContent(param_json);
            //getFomartDate() 格式化时间
            esLogBean.setCreateTime(DateUtils.getFomartDate(new Date()));//.field("format","yyyy-mm-dd HH:mm:ss")
            //请求到达时间-调用成功后的时间
            long receiveTime = (long)context.get("receiveTime");
            esLogBean.setPlatformRepTime(System.currentTimeMillis()-receiveTime);//执行api  需要时间
            esLogBean.setReceiveTime(receiveTime);
            esLogBean.setServIP(request.getLocalAddr());
            esLogBean.setErrorCode(ExceptionDict.SUCCESS);

            //System.out.println("-------->"+esLogBean);
            String json = JSON.toJSONString(esLogBean);

            rabbitTemplate.convertAndSend(SysConstant.QUEUE_NAME,json);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
